const express = require("express");
const jwt = require("jsonwebtoken");
const md5 = require("md5");
const UserModel = require("../../models/UserModel");
const router = express.Router();
const { SECRET } = require("../../config");

router.post("/login", (req, res) => {
  const { username, password } = req.body;
  UserModel.findOne({ username, password: md5(password) }, (err, data) => {
    if (err) {
      return res.json({
        code: "20001",
        msg: "数据库读取失败",
        data: null,
      });
    }

    // 数据库没有查询到该数据
    if (!data) {
      return res.json({
        code: "2002",
        msg: "账号或密码错误",
        data: null,
      });
    }

    // 登录成功逻辑
    let token = jwt.sign({ username: data.username, _id: data._id }, SECRET, {
      expiresIn: 60 * 60 * 24 * 7,
    });
    res.json({
      code: "00000",
      msg: "登录成功",
      data: token,
    });

    // req.session.username = data.username;
    // req.session._id = data._id;

    // res.render("success", { msg: "登录成功", url: "/account" });
  });
});

// 退出登录
router.post("/logout", (req, res) => {
  req.session.destroy(() => {
    res.render("success", { msg: "退出登录成功", url: "/login" });
  });
});

module.exports = router;
